<template>
	<div class="roleManage">
		<div class="public-search-box">
			<el-form ref="form"
					 inline
					 :model="searchData"
					 label-width="80px">
				<el-form-item>
					<el-input v-model="searchData.name"
							  clearable
							  size="small"
							  placeholder="名称"
							  style="width: 200px;"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"
							   size="small"
							   icon="el-icon-search"
							   v-if="hasPerm('role:list')"
							   @click="pageChange(1, 10)">搜索
					</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"
							   size="small"
							   icon="el-icon-plus"
							   v-if="hasPerm('role:add')"
							   @click="addOrUpdate('add')">新增
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="public-table"
			 v-loading="loading"
			 element-loading-text="拼命加载中...">
			<el-table :data="listData"
					  height="calc(100vh - 114px - 30px - 61px - 72px - 30px)"
					  style="width: 100%">
				<el-table-column prop="orderNumber"
								 label="序号"
								 align="center"
								 width="180">
				</el-table-column>
				<el-table-column prop="name"
								 label="角色名称"
								 align="center"
								 width="180">
				</el-table-column>
				<el-table-column prop="sort"
								 label="排序"
								 align="center"
								 width="180">
				</el-table-column>
				<el-table-column prop="created_time"
								 align="center"
								 label="创建时间">
					<template slot-scope='scope'>
						<span>{{ scope.row.created_time | dateTime }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="updated_time"
								 align="center"
								 label="更新时间">
					<template slot-scope='scope'>
						<span>{{ scope.row.updated_time | dateTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作"
								 align="center">
					<template slot-scope="scope">
						<el-button type="primary"
								   size="small"
								   v-if="hasPerm('role:detail')"
								   @click="see(scope.row)">查看
						</el-button>
						<el-button type="info"
								   size="small"
								   v-if="hasPerm('role:edit')"
								   @click="addOrUpdate('update', scope.row)">修改
						</el-button>
						<el-button type="danger"
								   size="small"
								   v-if="hasPerm('role:delete')"
								   @click="del(scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination :total="total"
					:page="searchData.currentPage"
					:pageSize="searchData.pageSize"
					@pageChange="pageChange"></pagination>
		<el-dialog :title="dialogTitle"
				   :visible.sync="addOrUpdateVisible"
				   width="500px"
				   custom-class="public-dialog"
				   :close-on-click-modal="false"
				   :close-on-press-escape="false"
				   :before-close="addOrUpdateClose">
			<el-form ref="addOrUpdateRef"
					 :model="addOrUpdateData"
					 :rules="addOrUpdateRules"
					 :disabled="isDisabled"
					 label-width="90px">
				<el-form-item label="角色名称:"
							  prop="name"
							  size="small">
					<el-input v-model="addOrUpdateData.name"></el-input>
				</el-form-item>
				<el-form-item label="排序:"
							  prop="sort"
							  size="small">
					<el-input-number v-model="addOrUpdateData.sort"
									 label="描述文字"></el-input-number>
				</el-form-item>
				<el-form-item label="状态:"
							  prop="status"
							  size="small">
					<el-radio-group v-model="addOrUpdateData.status">
						<el-radio :label="0">正常</el-radio>
						<el-radio :label="1">停用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="菜单:"
							  prop="email"
							  size="small">
					<el-tree ref="menuTree"
							 node-key="id"
							 show-checkbox
							 default-expand-all
							 check-on-click-node
							 :data="menuList"
							 :props="defaultProps"
							 :check-strictly="true"
							 :default-checked-keys="defaultMenu"
							 @check-change="menuCheckChange"></el-tree>
				</el-form-item>
			</el-form>
			<span slot="footer"
				  class="dialog-footer">
                <el-button size="small"
						   @click="addOrUpdateClose">取 消</el-button>
                <el-button type="primary"
						   size="small"
						   v-if="!isDisabled"
						   @click="addOrUpdateSubmit">确 定</el-button>
            </span>
		</el-dialog>
	</div>
</template>

<script>
import pagination from '@/components/pagination/pagination'
import { roleApi, menuApi } from '@/api'
import { numSort, handleTree } from '@/utils'

export default {
	name: 'roleManage',
	data () {
		let validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'))
			} else if (value !== this.addOrUpdateData.password) {
				callback(new Error('两次输入密码不一致!'))
			} else {
				callback()
			}
		}
		return {
			searchData: {
				username: '',
				nickname: '',
				currentPage: 1,
				pageSize: 10
			},
			loading: true,
			total: 100,
			listData: [],
			addOrUpdateVisible: false,
			passShow: true, // 是否显示密码框
			isDisabled: false,
			addOrUpdateData: {
				id: '',
				name: '',
				sort: 0,
				status: 0,
				menu: ''
			},
			defaultMenu: [],
			menuList: [],
			defaultProps: {
				children: 'children',
				label: 'name'
			},
			addOrUpdateRules: {
				name: {
					required: true,
					message: '请输入角色名称',
					trigger: 'blur'
				},
				sort: {
					required: true,
					message: '角色顺序不能为空',
					trigger: 'blur'
				}
			}
		}
	},
	mounted () {
		this.getList()
	},
	methods: {
		// 查询列表
		async getList () {
			this.loading = true
			let params = Object.assign({}, this.searchData)
			const { data, err } = await roleApi.getPage(params)
			if (err) {
				return false
			}
			if (data.list.length === 0 && params.currentPage !== 1) {
				// 删除后判断当前页面是否无数据 如果有数据则正常处理数据，如不正常数据为空时。则重新获取有数据的页面条件
				// 删除后当前页面无数据时，则重新计算有数据的页面重新获取数据
				let current = Math.ceil(data.totalCount / params.pageSize)
				this.pageChange(current)
			} else {
				data.list.forEach((item, index) => {
					item['orderNumber'] = numSort(
						index,
						params.currentPage,
						params.pageSize
					)
				})
				this.listData = data.list
				this.total = data.totalCount
				setTimeout(() => {
					this.loading = false
				}, 100)
			}
		},
		async getMenuList () {
			const { err, data } = await menuApi.getList()
			if (err) {
				return false
			}
			this.menuList = handleTree(data)
		},
		// 新增或者修改
		addOrUpdate (val, item) {
			this.addOrUpdateVisible = true
			this.isDisabled = false
			this.getMenuList()
			if (val === 'add') {
				this.passShow = true
			} else if (val === 'update') {
				this.passShow = false
				this.getDetail(item)
			}
		},
		// 查看
		see (item) {
			this.addOrUpdateVisible = true
			this.passShow = false
			this.isDisabled = true
			this.getDetail(item)
		},
		// 查看详情
		async getDetail (item) {
			this.defaultMenu = []
			const { err, data } = await roleApi.detailData(item.id)
			if (err) {
				return false
			}
			this.addOrUpdateData.id = data.id
			this.addOrUpdateData.name = data.name
			this.addOrUpdateData.sort = data.sort
			this.addOrUpdateData.status = data.status
			this.defaultMenu = data.menu.split(',')
		},
		// 新增或修改提交
		addOrUpdateSubmit () {
			let api = null
			let message = ''
			this.$refs['addOrUpdateRef'].validate(async (valid) => {
				if (valid) {
					let params = Object.assign({}, this.addOrUpdateData)
					if (params.id === '') {
						api = roleApi.addData
						message = '添加成功'
						delete params.id
					} else {
						api = roleApi.updateData
						message = '更新成功'
					}
					const { err, data } = await api(params)
					if (err) {
						return false
					}
					this.$message({
						message: message,
						type: 'success'
					})
					this.addOrUpdateClose()
					this.getList()
				} else {
					return false
				}
			})
		},
		menuCheckChange () {
			let arr = this.$refs['menuTree'].getCheckedNodes()
			let newArr = arr.map((item) => {
				return item.id
			})
			this.addOrUpdateData.menu = newArr.join(',')
		},
		// 弹框关闭
		addOrUpdateClose () {
			this.addOrUpdateVisible = false
			this.addOrUpdateData.id = ''
			this.$refs['addOrUpdateRef'].resetFields()
		},
		// 删除
		del (item) {
			this.$confirm('确定删除当前数据吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const { err, data } = await roleApi.delData(item)
				if (err) {
					return false
				}
				this.$message({
					message: '删除成功',
					type: 'success'
				})
				this.getList()
			}).catch(() => {})
		},
		pageChange (val, size) {
			if (size) {
				this.searchData.pageSize = size
			}
			this.searchData.currentPage = val
			this.getList()
		}
	},
	computed: {
		dialogTitle: function () {
			let str = this.addOrUpdateData.id === '' ? '新增' : '修改'
			if (this.isDisabled) {
				str = '查看'
			}
			return `${str}管理员`
		}
	},
	components: { pagination }
}
</script>

<style lang="less" scoped>
.roleManage {
	width: 100%;
}
</style>
